package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.item.feign.ItemFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/9/27 15:42 星期二
 * description:
 */
@Controller
@RequestMapping("/page/item")
public class ItemController {

    @Autowired
    private ItemFeign itemFeign;

    /**
     * 打开商品详情页
     * @param skuId
     * @return
     */
    @GetMapping
    public String item(Long skuId,
                       Model model){
        //远程调用商品详情微服务查询商品详情的6块数据
        Map<String, Object> result = itemFeign.getItemInfo(skuId);
        //存入model
        model.addAllAttributes(result);
        //返回页面
        return "item";
    }

    @Autowired
    private TemplateEngine templateEngine;
    /**
     * 使用模板引擎根据skuId生成静态页面
     * @param skuId
     * @return
     */
    @GetMapping(value = "/createSkuHtml")
    public String createSkuHtml(Long skuId) throws Exception{
        //查询商品的六块数据
        Map<String, Object> result = itemFeign.getItemInfo(skuId);
        if(result == null){
            return "生成失败,商品不存在";
        }

        //初始化数据容器
        Context context = new Context();
        context.setVariables(result);
        //初始化文件对象
        File file = new File("D:\\JAVA0409\\gmall\\gmall-parent\\web\\web-all\\src\\main\\resources\\templates",
                skuId + ".html");
        //初始化数据输出流
        PrintWriter printWriter = new PrintWriter(file,"UTF-8");
        /**
         * 1.使用哪个页面作为模板
         * 2.使用哪个容器装数据
         * 3.保存到哪里去
         */
        templateEngine.process("itemModel",context,printWriter);

        //刷新流并关闭
        printWriter.flush();
        printWriter.close();

        return skuId + "的静态页面生成成功!";
    }
}
